/*
  Simple DirectMedia Layer
  Copyright (C) 1997-2022 Sam Lantinga <slouken@libsdl.org>

  This software is provided 'as-is', without any express or implied
  warranty.  In no event will the authors be held liable for any damages
  arising from the use of this software.

  Permission is granted to anyone to use this software for any purpose,
  including commercial applications, and to alter it and redistribute it
  freely, subject to the following restrictions:

  1. The origin of this software must not be misrepresented; you must not
     claim that you wrote the original software. If you use this software
     in a product, an acknowledgment in the product documentation would be
     appreciated but is not required.
  2. Altered source versions must be plainly marked as such, and must not be
     misrepresented as being the original software.
  3. This notice may not be removed or altered from any source distribution.
*/
#include "../../SDL_internal.h"

#if SDL_AUDIO_DRIVER_NXOS

/* Allow access to a raw mixing buffer */

#include <nxos.h>

#include <errno.h>
#include <string.h>

#include "SDL_audio.h"
#include "../SDL_audio_c.h"
#include "../SDL_audiodev_c.h"
#include "SDL_nxosaudio.h"

static void
NXOS_CloseDevice(_THIS)
{
    if (this->hidden->audio_solt >= 0) {
        NX_DeviceClose(this->hidden->audio_solt);
    }
    SDL_free(this->hidden->mixbuf);
    SDL_free(this->hidden);
}


static int
NXOS_OpenDevice(_THIS, const char *devname)
{
    SDL_bool iscapture = this->iscapture;
    int format;
    int value;
    NX_U32 test_format;

    /* We don't care what the devname is...we'll try to open anything. */
    /*  ...but default to first name in the list... */
    if (devname == NULL) {
        devname = "sb16"; /* default sb16 device */
    }

    /* Make sure fragment size stays a power of 2, or OSS fails. */
    /* I don't know which of these are actually legal values, though... */
    if (this->spec.channels > 8)
        this->spec.channels = 8;
    else if (this->spec.channels > 4)
        this->spec.channels = 4;
    else if (this->spec.channels > 2)
        this->spec.channels = 2;

    /* Initialize all variables that we clean on shutdown */
    this->hidden = (struct SDL_PrivateAudioData *)
        SDL_malloc((sizeof *this->hidden));
    if (this->hidden == NULL) {
        return SDL_OutOfMemory();
    }
    SDL_zerop(this->hidden);

    /* Open the audio device */
    this->hidden->audio_solt = NX_DeviceOpen(devname, 0);
    if (this->hidden->audio_solt < 0) {
        return SDL_SetError("Couldn't open %s: %s", devname, strerror(errno));
    }

    /* Get a list of supported hardware formats */
    if (NX_DeviceControl(this->hidden->audio_solt, NX_AUDIO_GET_FMTS, &value) != NX_EOK) {
        perror("NX_AUDIO_GET_FMTS");
        return SDL_SetError("Couldn't get audio format list");
    }

    /* Try for a closest match on audio format */
    format = 0;
    for (test_format = SDL_FirstAudioFormat(this->spec.format);
         !format && test_format;) {
#ifdef DEBUG_AUDIO
        fprintf(stderr, "Trying format 0x%4.4x\n", test_format);
#endif
        switch (test_format) {
        case AUDIO_U8:
            if (value & NX_AUDIO_FTM_U8) {
                format = NX_AUDIO_FTM_U8;
            }
            break;
        case AUDIO_S16LSB:
            if (value & NX_AUDIO_FTM_S16_LE) {
                format = NX_AUDIO_FTM_S16_LE;
            }
            break;
        case AUDIO_S16MSB:
            if (value & NX_AUDIO_FTM_S16_BE) {
                format = NX_AUDIO_FTM_S16_BE;
            }
            break;
        case AUDIO_S8:
            if (value & NX_AUDIO_FTM_S8) {
                format = NX_AUDIO_FTM_S8;
            }
            break;
        case AUDIO_U16LSB:
            if (value & NX_AUDIO_FTM_U16_LE) {
                format = NX_AUDIO_FTM_U16_LE;
            }
            break;
        case AUDIO_U16MSB:
            if (value & NX_AUDIO_FTM_U16_BE) {
                format = NX_AUDIO_FTM_U16_BE;
            }
            break;
        default:
            format = 0;
            break;
        }
        if (!format) {
            test_format = SDL_NextAudioFormat();
        }
    }
    if (format == 0) {
        return SDL_SetError("Couldn't find any hardware audio formats");
    }
    this->spec.format = test_format;

    /* Set the audio format */
    value = format;
    if ((NX_DeviceControl(this->hidden->audio_solt, NX_AUDIO_SET_FMT, &value) != NX_EOK) ||
        (value != format)) {
        perror("NX_AUDIO_SET_FMT");
        return SDL_SetError("Couldn't set audio format");
    }

    /* Set the number of channels of output */
    value = this->spec.channels;
    if (NX_DeviceControl(this->hidden->audio_solt, NX_AUDIO_SET_CHANNELS, &value) != NX_EOK) {
        perror("NX_AUDIO_SET_CHANNELS");
        return SDL_SetError("Cannot set the number of channels");
    }
    this->spec.channels = value;

    /* Set the DSP frequency */
    value = this->spec.freq;
    if (NX_DeviceControl(this->hidden->audio_solt, NX_AUDIO_SET_SPEED, &value) != NX_EOK) {
        perror("NX_AUDIO_SET_SPEED");
        return SDL_SetError("Couldn't set audio frequency");
    }
    this->spec.freq = value;

    /* Calculate the final parameters for this audio specification */
    SDL_CalculateAudioSpec(&this->spec);

    /* Allocate mixing buffer */
    if (!iscapture) {
        this->hidden->mixlen = this->spec.size;
        this->hidden->mixbuf = (Uint8 *) SDL_malloc(this->hidden->mixlen);
        if (this->hidden->mixbuf == NULL) {
            return SDL_OutOfMemory();
        }
        SDL_memset(this->hidden->mixbuf, this->spec.silence, this->spec.size);
    }

    /* We're ready to rock and roll. :-) */
    return 0;
}


static void
NXOS_PlayDevice(_THIS)
{
    struct SDL_PrivateAudioData *h = this->hidden;
    if (NX_DeviceWrite(h->audio_solt, h->mixbuf, 0, h->mixlen) <= 0) {
        perror("Audio write");
        SDL_OpenedAudioDeviceDisconnected(this);
    }
#ifdef DEBUG_AUDIO
    fprintf(stderr, "Wrote %d bytes of audio data\n", h->mixlen);
#endif
}

static Uint8 *
NXOS_GetDeviceBuf(_THIS)
{
    return (this->hidden->mixbuf);
}

static SDL_bool
NXOS_Init(SDL_AudioDriverImpl * impl)
{
    /* Set the function pointers */
    impl->OpenDevice = NXOS_OpenDevice;
    impl->PlayDevice = NXOS_PlayDevice;
    impl->GetDeviceBuf = NXOS_GetDeviceBuf;
    impl->CloseDevice = NXOS_CloseDevice;

    impl->OnlyHasDefaultOutputDevice = SDL_TRUE;

    return SDL_TRUE;   /* this audio target is available. */
}


AudioBootStrap NXOSAUDIO_bootstrap = {
    "nxos", "NXOS audio", NXOS_Init, SDL_FALSE
};

#endif /* SDL_AUDIO_DRIVER_NXOS */

/* vi: set ts=4 sw=4 expandtab: */
